package com.study.service.hystrix;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.study.service.NacosClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class UseHystrixCommandAnnotation {

    @Autowired
    private NacosClientService nacosClientService;

    @HystrixCommand(
            groupKey = "nacosClientService",
            commandKey = "nacosClientService",
            threadPoolKey = "nacosClientService",
            fallbackMethod = "getNacosClientInfoFallback",
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMillisecond",value = "1500"),
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "10")
            },
            //舱壁模式
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize",value = "30"),
                    @HystrixProperty(name = "maxQueueSize",value = "101"),
                    @HystrixProperty(name = "keepAliveTimeMinutes",value = "2"),
                    @HystrixProperty(name = "queueSizeRejectionThreshold",value = "15"),
                    @HystrixProperty(name = "metrics.rollingStats.numBuckets",value = "12"),
                    @HystrixProperty(name = "metrics.rollingStats.timeInMillseconds",value = "12")
            }
    )
    public List<ServiceInstance> getNacosClientInfo(String serviceId){

        //测试 UseHystrixCommandAnnotation 超时
        try {
            //"execution.isolation.thread.timeoutInMillisecond",value = "1500"
            //比2000小、所以执行本类的getNacosClientInfoFallback()方法
            Thread.sleep(2000);
        }catch (Exception e){
        }


        log.info("使用 hystrix command 注解 get nacos client 信息 : [{}],[{}]",
                serviceId,Thread.currentThread().getName());
        return nacosClientService.getNacosClientInfo(serviceId);
    }

    public List<ServiceInstance> getNacosClientInfoFallback(String serviceId){

        log.warn("不能获取 nacos client,trigger hystrix fallback: [{}],[{}]",
                serviceId,Thread.currentThread().getName());
        return Collections.emptyList();

    }


}
